package ordered;

import iterator.Iterator;
import visitor.Visitor;
import wrapper.Comparable;
import container.AbstractSearchableContainer;
import container.ContainerEmptyException;
import enumeration.Enumeration;

public class OrderedListAsLinkedList extends AbstractSearchableContainer
		implements OrderedList {
	protected LinkedList linkedList;

	public OrderedListAsLinkedList() {
		linkedList = new LinkedList();
	}

	public void insert(Comparable object) {
		linkedList.append(object);
		++count;
	}

	public Comparable get(int offset) {
		if (offset < 0 || offset >= count)
			throw new IndexOutOfBoundsException();

		LinkedList.Element ptr = linkedList.getHead();
		for (int i = 0; i < offset && ptr != null; ++i)
			ptr = ptr.getNext();
		return (Comparable) ptr.getDatum();
	}

	public boolean isMember(Comparable object) {
		for (LinkedList.Element ptr = linkedList.getHead(); ptr != null; ptr = ptr
				.getNext()) {
			if ((Comparable) ptr.getDatum() == object)
				return true;
		}
		return false;
	}

	public Comparable find(Comparable arg) {
		for (LinkedList.Element ptr = linkedList.getHead(); ptr != null; ptr = ptr
				.getNext()) {
			Comparable object = (Comparable) ptr.getDatum();
			if (object.isEQ(arg))
				return object;
		}
		return null;
	}

	public void withdraw(Comparable object) {
		if (count == 0)
			try {
				throw new ContainerEmptyException();
			} catch (ContainerEmptyException e) {
				System.out.println("A lista está vazia!");
			}
		linkedList.extract(object);
		--count;
	}

	protected class MyCursor implements Cursor {
		LinkedList.Element element;

		MyCursor(LinkedList.Element element) {
			this.element = element;
		}

		public Comparable getDatum() {
			return (Comparable) element.getDatum();
		}

		public void insertAfter(Comparable object) {
			element.insertAfter(object);
			++count;
		}

		public void withdraw() {
			linkedList.extract(element.getDatum());
			--count;
		}

		public void insertBefore(Comparable object) {
			element.insertBefore(object);
			++count;
		}
	}

	public Cursor findPosition(Comparable arg) {
		LinkedList.Element ptr;
		for (ptr = linkedList.getHead(); ptr != null; ptr = ptr.getNext()) {
			Comparable object = (Comparable) ptr.getDatum();
			if (object.isEQ(arg))
				break;
		}
		return new MyCursor(ptr);
	}

	@Override
	protected int compareTo(Comparable arg) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void accept(Visitor visitor) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Enumeration getEnumeration() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Iterator getIterator() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void purge() {
		// TODO Auto-generated method stub
		
	}



}